package com.inter.controller.insidetask;

import com.inter.entity.bak.InternationalPayPackage;
import com.inter.entity.common.DevicePackageCoverPicture;
import com.inter.entity.common.Partner;
import com.inter.entity.common.PartnerProductPackage;
import com.inter.entity.newpojo.Constant;
import com.inter.entity.newpojo.TurntoInterfaceUtils;
import com.inter.entity.newpojo.request.RequestBody.SyncModulePackagesRequestBody;
import com.inter.entity.newpojo.request.RequestHeader;
import com.inter.entity.newpojo.request.subRequest.SyncModulePackagesRequest;
import com.inter.entity.newpojo.response.responseBody.SyncPackagesResponse;
import com.inter.entity.newpojo.response.subResponse.common._Package;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.utils.HttpClientTool;
import com.inter.utils.JaxbUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 2.0:第二版同步套餐接口：带着packageStatus
 * <p>
 * http://localhost:8083/gateway/syncData
 *
 * @author lm
 * @date 2019/07/15
 */

@Configuration
@EnableScheduling
@RestController
public class SyncPartnerPackageStatusController {

    private static Logger logger = Logger.getLogger(SyncPartnerPackageStatusController.class);

    @Autowired
    PartnerService partnerService;

    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    // 每天晚上凌晨1点执行一次

    //@Scheduled(cron = "0 0 1 * * ?")

    @RequestMapping(value = "syncData", method = RequestMethod.GET)
    @ResponseBody
    public void syncData() {

        logger.info("每天凌晨1点执行的获取企业套餐的任务执行开始！");
        //1，取数据库取partnerCode出来
        List<Partner> partnerList = partnerService.findPartnerCode();

        for (Partner partner : partnerList) {

            //String partnerCode = "P001018";
            String partnerCode = partner.getPartnerCode();

            String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
            String secret = partnerService.findSecretByPartnerCode(partnerCode);
            // 2,生成当前时间戳
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String curtime = df.format(new Date());

            String sign = "";
            // 请求参数拼接
            SyncModulePackagesRequest request = new SyncModulePackagesRequest();
            TurntoInterfaceUtils utils = new TurntoInterfaceUtils();
            RequestHeader header = utils.getRequestHeader(Constant.cmd_syncPackages, partnerCode);
            request.setHeader(header);
            SyncModulePackagesRequestBody body = new SyncModulePackagesRequestBody();
            request.setBody(body);

            try {
                sign = utils.getSign(header, body, body.getClass(), secret);
                request.setSign(sign);
            } catch (Exception e) {
                logger.info("计算签名捕获到异常：" + e);
                e.printStackTrace();
            }

            // 将参数转换成XML格式
            String sRequest = new JaxbUtil(SyncModulePackagesRequest.class).toXml(request, "utf-8");
            logger.info("【同步套餐】请求：" + sRequest);
            // 发送post请求，并接收返回结果
            String result = HttpClientTool.sendHttpPost(Constant.BASE_URL, sRequest);
            logger.info("【同步套餐】响应：" + result);

            if (!result.equals("-1")) {

                // 将回传的xml转换成object数据

                SyncPackagesResponse responseObj = new JaxbUtil(SyncPackagesResponse.class).fromXml(result, "utf-8");

                if (responseObj != null) {
                    String retCode = responseObj.getHeader().getResultCode();
                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(retCode)) {
                        // 将SyncModulePackagesResponse收到的package遍历出来
                        List<_Package> packageList = responseObj.getBody().get_package();

                        if (packageList != null || !packageList.isEmpty() || packageList.size() > 0) {
                            // 普通套餐
                            for (_Package p : packageList) {

                                String packageCode = p.getPackageCode();
                                String coverCountrys = p.getCoverCountrys();

                                String mccs = "";
                                String continentName = "";
                                String continentNameEN = "";
                                String coverCountrysEN = "";
                                String coverCountryCode = "";

                                //将mcc用；截取，然后拿着数据去查询
                                String[] strs = coverCountrys.split(";");

                                for (int i = 0; i < strs.length; i++) {

                                    mccs = strs[i];

                                    continentName += partnerProductPackageService.queryContinent(mccs) + ";";
                                    continentNameEN += partnerProductPackageService.queryContinentEN(mccs) + ";";
                                    coverCountrysEN += partnerProductPackageService.queryCountryEN(mccs) + ";";
                                }

                                // 最后一个，去掉
                                if (!"".equals(continentName) || !"".equals(coverCountrys)) {
                                    continentName = continentName.substring(0, continentName.length() - 1);
                                    continentNameEN = continentNameEN.substring(0, continentNameEN.length() - 1);
                                    coverCountrysEN = coverCountrysEN.substring(0, coverCountrysEN.length() - 1);
                                }

                                // coverCountryCode值选用用来标识图片的唯一性，所以要用partnerCode_packageCode组合来标识
                                coverCountryCode = partnerCode + "_" + packageCode;

                                int count = partnerProductPackageService.findPackageByPartnerCodeAndPackageCode(packageCode, partnerCode);

                                if (count <= 0) {

                                    //if (p.getStatus().equals("1")) {

                                    //可用

                                    if (p.getStatus().equals("2")) {

                                        PartnerProductPackage product = new PartnerProductPackage();
                                        product.setPartnerCode(partnerCode);
                                        product.setPartnerName(partnerName);
                                        product.setPackageType(p.getPackageType());
                                        product.setPackageCode(p.getPackageCode());
                                        product.setPackageName(p.getPackageName());
                                        product.setPackageNameEN(p.getPacakgeNameEn());
                                        product.setPackageDesc(p.getPackageDesc());
                                        product.setCoverCountryMcc(p.getCoverCountryMcc());
                                        product.setCoverCountrys(p.getCoverCountrys());
                                        product.setCoverCountryCode(coverCountryCode);
                                        product.setCoverCountrysEN(coverCountrysEN);
                                        product.setContinentName(continentName);
                                        product.setContinentNameEN(continentNameEN);
                                        product.setPriceType(p.getPriceType());
                                        product.setPackageFlow(p.getPackageFlow());
                                        product.setBuyType(p.getBuyType());
                                        product.setMinOrderPeriod(p.getMinOrderPeriod());
                                        product.setMaxOrderPeriod(p.getMaxOrderPeriod());
                                        product.setRefuelingPackageList("0");
                                        product.setStatus("0");
                                        product.setPackageStatus(p.getStatus());
                                        product.setPackage_usage_attribute(p.getPackage_usage_attribute());
                                        // 如果数据库中不存在当前套餐就入库套餐
                                        partnerProductPackageService.storageData(product);
                                        //logger.info("partner_product_t渠道套餐入库完成！");

                                        //bak版本：
                                        InternationalPayPackage payPackage = new InternationalPayPackage();
                                        payPackage.setPartnerCode(partnerCode);
                                        payPackage.setPartnerName(partnerName);
                                        payPackage.setPackageType(p.getPackageType());
                                        payPackage.setPackageCode(packageCode);
                                        payPackage.setPackageName(p.getPackageName());
                                        payPackage.setCoverCountryCode(coverCountryCode);
                                        payPackage.setStatus("0");
                                        payPackage.setBuyType(p.getBuyType());
                                        payPackage.setCoverCountryMcc(p.getCoverCountryMcc());
                                        payPackage.setCoverCountrys(coverCountrys);
                                        payPackage.setContinentName(continentName);
                                        payPackage.setMaxDays(p.getMaxOrderPeriod());
                                        payPackage.setMinDays(p.getMinOrderPeriod());
                                        partnerProductPackageService.bak_storagePackage(payPackage);
                                        //logger.info("device_package_international_pay_t渠道套餐入库完成！");
                                    }
                                    //停用
                                    else if (p.getStatus().equals("3")) {

                                        PartnerProductPackage product = new PartnerProductPackage();
                                        product.setPartnerCode(partnerCode);
                                        product.setPartnerName(partnerName);
                                        product.setPackageType(p.getPackageType());
                                        product.setPackageCode(p.getPackageCode());
                                        product.setPackageName(p.getPackageName());
                                        product.setPackageNameEN(p.getPacakgeNameEn());
                                        product.setPackageDesc(p.getPackageDesc());
                                        product.setCoverCountryMcc(p.getCoverCountryMcc());
                                        product.setCoverCountrys(p.getCoverCountrys());
                                        product.setCoverCountryCode(coverCountryCode);
                                        product.setCoverCountrysEN(coverCountrysEN);
                                        product.setContinentName(continentName);
                                        product.setContinentNameEN(continentNameEN);
                                        product.setPriceType(p.getPriceType());
                                        product.setPackageFlow(p.getPackageFlow());
                                        product.setBuyType(p.getBuyType());
                                        product.setMinOrderPeriod(p.getMinOrderPeriod());
                                        product.setMaxOrderPeriod(p.getMaxOrderPeriod());
                                        product.setRefuelingPackageList("0");
                                        product.setStatus("4");
                                        product.setPackageStatus(p.getStatus());
                                        product.setPackage_usage_attribute(p.getPackage_usage_attribute());
                                        // 如果数据库中不存在当前套餐就入库套餐
                                        partnerProductPackageService.storageData(product);
                                        //logger.info("partner_product_t渠道套餐入库完成！");

                                        //bak版本：
                                        InternationalPayPackage payPackage = new InternationalPayPackage();
                                        payPackage.setPartnerCode(partnerCode);
                                        payPackage.setPartnerName(partnerName);
                                        payPackage.setPackageType(p.getPackageType());
                                        payPackage.setPackageCode(packageCode);
                                        payPackage.setPackageName(p.getPackageName());
                                        payPackage.setCoverCountryCode(coverCountryCode);
                                        payPackage.setStatus("4");
                                        payPackage.setBuyType(p.getBuyType());
                                        payPackage.setCoverCountryMcc(p.getCoverCountryMcc());
                                        payPackage.setCoverCountrys(coverCountrys);
                                        payPackage.setContinentName(continentName);
                                        payPackage.setMaxDays(p.getMaxOrderPeriod());
                                        payPackage.setMinDays(p.getMinOrderPeriod());
                                        partnerProductPackageService.bak_storagePackage(payPackage);
                                        //logger.info("device_package_international_pay_t渠道套餐入库完成！");

                                    }

                                } else {//已经有这条数据，我们需要去比对套餐的状态是不是还有效,另外需要去比较一下现在数据库的package_usage_attribute这个值是否有

                                    // 第一步，无论如何都先去更新一下package_usage_attribute这个值：
                                    // 这一步暂时不需要Travis的值是在深圳改的，所以不要更新了

//                                    PartnerProductPackage pro = new PartnerProductPackage();
//                                    pro.setPartnerCode(partnerCode);
//                                    pro.setPackageCode(packageCode);
//                                    pro.setPackage_usage_attribute(p.getPackage_usage_attribute());
//                                    partnerProductPackageService.update_package_usage_attribute(pro);

                                    // 第二步：

                                    String statusStr = partnerProductPackageService.queryPackageStatusByCode(packageCode, partnerCode);

                                    //获取到的套餐的状态跟数据库的状态不一样，此时要更新数据库
                                    //获取到的数据是3（停售），数据库的状态是2（启用），此时要更新数据库，将销售状态改成4（停售），将套餐状态值改成3（停售）

                                    if (statusStr.equals("1") && !p.getStatus().equals(statusStr)) {

                                        PartnerProductPackage product = new PartnerProductPackage();
                                        product.setPartnerCode(partnerCode);
                                        product.setPackageCode(packageCode);
                                        product.setPackageStatus(p.getStatus());
                                        product.setStatus("4");
                                        partnerProductPackageService.updatePackageStatus(product);

                                    } else {
                                        continue;
                                    }
                                }

                                //图片信息入库
                                int c = partnerProductPackageService.findPictureExistOrNot(packageCode, partnerCode);

                                if (c <= 0) {

                                    DevicePackageCoverPicture picture = new DevicePackageCoverPicture();
                                    picture.setPartnerCode(partnerCode);
                                    picture.setPartnerName(partnerName);
                                    picture.setPackageCode(packageCode);
                                    picture.setCoverCountryCode(coverCountryCode);
                                    picture.setCoverCountrys(coverCountrys);
                                    picture.setCreateTime(curtime);
                                    partnerProductPackageService.storagePicture(picture);
                                    //logger.info("device_package_cover_picture_t入库完成！");

                                }
                            }

                        } else {
                            //logger.info("遍历结果为空，继续执行！");

                            continue;
                        }
                    } else {
                        //logger.info("发生了未知错误或者无资费套餐，继续执行！");
                        continue;
                    }

                } else {
                    //logger.info("未得到正常的报文返回，继续执行！");
                    continue;
                }

            } else {
                //logger.info("返回报文不正常为-1，继续执行！");
                continue;
            }
        }

        logger.info("每天凌晨1点执行的获取企业套餐的任务执行完毕！");
    }


}
